import { get, set } from 'lodash'

export default function createPersistedStatePlugin(options) {
  return async (store) => {
    const defaultOptions = {
      paths: undefined,
      key: 'my-vuex'
    }
    const { paths, key } = Object.assign(defaultOptions, options)
    if (Array.isArray(paths) && paths.length === 0) {
      return
    }

    const data = await new Promise((resolve) => {
      window.electron.ipcRenderer.once('get-state-reply', (event, arg) => {
        resolve(arg)
      })
      window.electron.ipcRenderer.send('get-state', { key })
    })
    // console.log('get-state-reply', data)
    // 获取持久化的状态
    function getPersistedState(state, paths) {
      if (!paths) {
        return state
      }
      return paths.reduce((acc, path) => {
        set(acc, path, get(state, path))
        return acc
      }, {})
    }

    const originalState = store.state
    let state
    if (data) {
      if (paths) {
        paths.forEach((path) => {
          set(originalState, path, get(data, path, get(originalState, path)))
        })
        state = originalState
      } else {
        state = data
      }
    } else {
      state = originalState
      const newState = getPersistedState(originalState, paths)
      window.electron.ipcRenderer.send('set-state', { key, state: newState })
    }

    store.replaceState(state)

    store.subscribe((mutation, state) => {
      if (!paths) {
        window.electron.ipcRenderer.send('set-state', { key, state })
      } else {
        const persistedRoot = paths.map((path) => path.split('.')[0])
        if (!persistedRoot.includes(mutation.type.split('/')[0])) {
          return
        }
        const newState = getPersistedState(state, paths)
        window.electron.ipcRenderer.send('set-state', { key, state: newState })
      }
    })
  }
}
